import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from '@/config';
import { ISession } from '@/pages/api';
import { prepareConnection } from '@/db';
import { User, Article, Tag } from '@/db/entity';
import { EXCEPTION_ARTICLE } from '@/pages/api/config/codes';

const publish = async (req: NextApiRequest, res: NextApiResponse) => {
  // 通过 session 获取发布人,不通过 接口拿
  const session: ISession = req.session;
  const { title = '', content = '', tagIds = [] } = req.body;
  const db = await prepareConnection();
  const userRepo = db.getRepository(User)
  const articleRepo = db.getRepository(Article)
  const tagRepo = db.getRepository(Tag)

  // 找到是谁发布的文章
  // where 参数用于指定查询条件，而不加 where 参数则会查找所有记录中的第一个记录
  const user = await userRepo.findOne({
    id: session.userId,
  })
  const tags = await tagRepo.find({
    where: tagIds?.map((tagId: number) => ({ id: tagId })),
  })

  const newTags = tags.map((tag) => {
    tag.article_count += 1
    return tag
  })

  const article = new Article()
  article.title = title
  article.content = content
  article.create_time = new Date()
  article.update_time = new Date()
  article.is_delete = 0
  article.views = 0
  article.tags = newTags

  if (user) {
    article.user = user;
  }

  const articleResult = await articleRepo.save(article)

  if (articleResult) {
    res.status(200).json({ data: articleResult, code: 200, msg: '发布成功' });
  } else {
    res.status(200).json({ ...EXCEPTION_ARTICLE.PUBLISH_FAILED });
  }


};

export default withIronSessionApiRoute(publish, ironOptions);
